#coding=utf-8
import os
import logging
import sae
import web
import cgi


# 只有在请求的方法是POST的情况下才允许设置上传的最大文件大小
# 设置为0表示无限制
cgi.maxlen = 10 * 1024 * 1024 # 10MB

#StorageName指的是在你SAE帐号下创建的Domain名称
StorageName= 'kkxueupload'

#url映射
urls = (
    '/', 'Hello',
    '/upload','Upload'
)

#render
app_root = os.path.dirname(__file__)
templates_root = os.path.join(app_root, 'templates')
render = web.template.render(templates_root)

class Hello:        
    def GET(self):
        return render.hello()    
    
    
class Upload:
    def GET(self):
        #如何使用SAE的Storage服务
        from sae.storage import Bucket
        bucket = Bucket(StorageName)
        filelist =  bucket.list()
        #logging.error(type(filelist))竟然是generator
        return render.upload(filelist)


    def POST(self):
        try:
            x = web.input(myfile={})
        except ValueError:
            return "上传文件超过10M!"
        #filedir = './upload'
        if 'myfile' in x: 
            filepath=x.myfile.filename.replace('\\','/')
            filename=filepath.split('/')[-1]
            #上传文件到SAE Storage
            try:
                from sae.storage import Bucket
                bucket = Bucket(StorageName)
                bucket.put_object(filename, x.myfile.file.read())
                fileURL = bucket.generate_url(filename)
                #print fileURL
            except Exception as e:
                logging.error(e)
                
        raise web.seeother('/upload')
        
#献给老婆的宣言，不想删，请绕行。。。
#不过这里倒是可以看到如何使用静态图片
class MerryXmas:        
    def GET(self):
        return render.merryxmas()
        
    
#使用webpy在SAE下创建wsgi应用
app = web.application(urls, globals()).wsgifunc()
application = sae.create_wsgi_app(app)